package com.guigu.dh.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.dh.common.result.Result;
import com.guigu.dh.listener.DictImportDataListener;
import com.guigu.dh.mapper.DictMapper;
import com.guigu.dh.pojo.cmn.Dict;
import com.guigu.dh.service.DictService;
import com.guigu.dh.vo.cmn.DictExcelVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 医院设置表 服务实现类
 * </p>
 *
 * @author DengHao
 * @since 2022-02-24
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    // 根据id查所有子节点
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildren(Long id) {
        // 根据id查询所有子节点
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);

        List<Dict> list = baseMapper.selectList(wrapper);

        // 循环，然后根据当前对象的id查询是否该对象拥有子节点，并设置相应的值
        for (Dict dict : list) {
            Boolean children = isChildren(dict.getId());
            dict.setHasChildren(children);
        }

        return list;
    }

    // 导出数据字典数据到Excel表格中
    @Override
    public void exportData(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        String fileName = "dictionary";
        response.setHeader("Content-disposition","attachment;filename=" + fileName + ".xlsx");
        // 查数据库
        List<Dict> list = baseMapper.selectList(null);
        List<DictExcelVO> excelVOList = new ArrayList<>();
        for (Dict dict : list) {
            DictExcelVO dictExcelVO = new DictExcelVO();
            dictExcelVO.setDictCode(dict.getDictCode());
            dictExcelVO.setId(String.valueOf(dict.getId()));
            dictExcelVO.setName(dict.getName());
            dictExcelVO.setValue(dict.getValue());
            dictExcelVO.setParentId(String.valueOf(dict.getParentId()));
            excelVOList.add(dictExcelVO);
        }

        // 调用写方法进行下载操作
        try {
            EasyExcel.write(response.getOutputStream(),DictExcelVO.class)
                    .sheet("数据字典").doWrite(excelVOList);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    // 根据数据字典编码查询
    private Dict getDictByDictCode(String dictCode){
        return baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
    }

    // 根据值查询
    @Override
    public Result findDictByValue(String dictCode, String value) {
        if (dictCode == null || dictCode.equals("")) {
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return Result.ok(dict.getName());
        } else {
            Dict one = this.getDictByDictCode(dictCode);
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            if (one != null){
                wrapper.eq("parent_id",one.getId());
                wrapper.eq("value",value);
                Dict dict = baseMapper.selectOne(wrapper);
                return Result.ok(dict.getName());
            } else {
                wrapper.eq("value",value);
                Dict dict = baseMapper.selectOne(wrapper);
                return Result.ok(dict.getName());
            }
        }

    }

    // 根据dictCode查询集合数据
    @Override
    public Result findDictByDictCode(String dictCode) {
        Dict one = this.getDictByDictCode(dictCode);
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",one.getId());
        List<Dict> dict = baseMapper.selectList(wrapper);
        return Result.ok(dict);
    }

    // 导入数据到数据库中的方法
    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictExcelVO.class,new DictImportDataListener(baseMapper))
                    .sheet().doRead();
        } catch (Exception exception){
            log.error("导入出现错误");
        }
    }

    // 根据id判断是否拥有子节点
    public Boolean isChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);

        Integer count = baseMapper.selectCount(wrapper);

        return count > 0;
    }
}
